#include "semaphore.h"
#include "cmsis_os.h"
#include <string>


Semaphore::Semaphore(int initialCount, int maximumCount)
{
    osSemaphoreAttr_t attr = {0};
    
    attr.name = "semaphore";
    m_semHandle = osSemaphoreNew(maximumCount, initialCount, &attr);
}

Semaphore::~Semaphore()
{
    osSemaphoreDelete(m_semHandle);
}

int Semaphore::GetCurrentCount()
{
    return osSemaphoreGetCount(m_semHandle);
}

bool Semaphore::TryAcquire()
{
    return osSemaphoreAcquire(m_semHandle, 0) == osOK;
}

bool Semaphore::Acquire(int timeout)
{
    if(timeout == -1)
    {
        timeout = osWaitForever;
    }
    return osSemaphoreAcquire(m_semHandle, timeout) == osOK;
}

void Semaphore::Release()
{
    osSemaphoreRelease(m_semHandle);
}

void Semaphore::Clear()
{
    while(osSemaphoreGetCount(m_semHandle) > 0)
    {
        osSemaphoreAcquire(m_semHandle, 0);
    }
}

Semaphore &Semaphore::Zero()
{
    Clear();
    return *this;
}
